#!/bin/ksh
#
# @(#)25        1.18  src/sysmgt/dsm/bin/wsmserver.sh, websm, r31a.hsc, hsc_wsm_101002 7/10/02 10:38:37
#

LANG_SAVE=$LANG

#238484: set to C if not en_US or C
if [ "$LANG" != "en_US" -a  "$LANG" != "C" ]; then
  export LANG=C
fi

OS=`/bin/uname -s`

INETD_CONF=/etc/inetd.conf
SERVICES=/etc/services
WEBSM_HOME=/usr/websm
CODEBASE=${WEBSM_HOME}/codebase
BIN=${WEBSM_HOME}/bin
SERVER_NAME=wsmserver
PATH=$PATH:/usr/bin
PORTPATH=/var/websm/data/wservers/
CFG_FILE=/var/websm/config/user_settings/websm.cfg
LOG_FILE=/var/websm/data/wserver.log
PORT=9090
GATE_SERVER=websmhttps
GATE_PORT=9092
CFG_FILE=/var/websm/config/user_settings/websm.cfg
JCB_PROPERTIES=${CODEBASE}/com/ibm/jcb/resources/JCB.properties

if [ "$OS" = "Linux" ] ; then 

# Linux do not have chservices, chsubserver and dspmsg scripts, so
# we created functions instead having to create new files altogether

 set -f			# this is so that the case statement will work

# This following function is only for Linux, it is already available
# as an executable on AIX

 function dspmsg
 {

   shift

   if [ "$1" == "-s" ]; then
     shift
     shift
   else
     shift
   fi
   echo $*
 }

 COMMAND_NAME=`/bin/basename $0`
 GREP_CMD="/bin/egrep"
 ECHO_CMD="/bin/echo"
 SED_CMD="/bin/sed"
 AWK_CMD="/bin/awk"
 CP_CMD="/bin/cp"
 RM_CMD="/bin/rm"
 CAT_CMD="/bin/cat"
 PS_CMD="/usr/bin/ps -e"
 AWK_CMD="/usr/bin/awk"
 KILL_CMD="kill -HUP"
 TMP_SERVICES="/tmp/tmp.services$$"

# This following function is only for Linux, it is already available
# as a shell script file on AIX

 function chservices
 {

   ACTION=
   SERVICE_NAME=
   PROTOCOL=
   PORT=
   NEW_SERVICE_NAME=
   NEW_PROTOCOL=
   NEW_PORT=
   ALIASES=

   SERVICES_USAGE="
   usage: ${COMMAND_NAME} [-a|-d|-c] -v service_name -p protocol -n port [-V new_service_name] [-P new_protocol] [-N new_port] [-u \"aliases [aliases]...\"]\n"

# Parse the command line arguments to find out what service
# is to be uncommented, commented, or added and if a configuration
# file is specified.
# The -u is followed by a list of alias names in quotes
# and it must be the last flag used on the command line.

   set -- `/usr/bin/getopt adcv:p:n:V:P:N:u: $*  2>/dev/null` 
   if [ $? != 0 ] ; then          # Test for syntax error
      dspmsg chservices.cat -s 1 1 "${SERVICES_USAGE}" $COMMAND_NAME
      exit 1
   fi
   while [ $1 != -- ]
   do
     case $1 in
	-a|-d|-c)		# Action is to add or delete the service
	    if [ -n "${ACTION}" ] ; then dspmsg chservices.cat -s 1 1 "$SERVICES_USAGE" ${COMMAND_NAME} ; exit 1 ; fi
	    ACTION=`expr "$1" : "-\(.\)"`
	    shift		# Shift past the flag
	    ;;
	-v)			# Then we need to get the SERVICE_NAME
	    SERVICE_NAME=$2	# to add to the services line
	    shift; shift   	# Shift past the flag and SERVICE_NAME
	    ;;
	-p)			# Then we need to get the PROTOCOL
	    PROTOCOL=$2		# to add to the services line
	    shift; shift   	# Shift past the flag and PROTOCOL
	    ;;
	-n)			# Then we need to get the PORT
	    PORT=$2		# to add to the services line
	    shift; shift   	# Shift past the flag and PORT
	    ;;
	-V)			# Then we need to get the NEW_SERVICE_NAME
	    NEW_SERVICE_NAME=$2	# to add to the services line
	    shift; shift   	# Shift past the flag and NEW_SERVICE_NAME
	    ;;
	-P)			# Then we need to get the NEW_PROTOCOL
	    NEW_PROTOCOL=$2	# to add to the services line
	    shift; shift   	# Shift past the flag and NEW_PROTOCOL
	    ;;
	-N)			# Then we need to get the NEW_PORT
	    NEW_PORT=$2		# to add to the services line
	    shift; shift   	# Shift past the flag and NEW_PORT
	    ;;
	-u)			# Then we need to get the list of ALIASES
	    ALIASES=$2		# to add to the end of the services line
	    shift; shift   	# Shift past the flag and ALIASES
	    ;;
	*)
	    dspmsg chservices.cat -s 1 1 "$SERVICES_USAGE" ${COMMAND_NAME}
	    exit 1
	    ;;
    esac
   done
   shift                   	# Shift past the "--" from getopt
 
   if [ -z "${SERVICE_NAME}" ] ; then          # Test for syntax error
      dspmsg chservices.cat -s 1 1 "${SERVICES_USAGE}" $COMMAND_NAME
      exit 1
   fi

   if [ -z "${PROTOCOL}" ] ; then          # Test for syntax error
       dspmsg chservices.cat -s 1 1 "${SERVICES_USAGE}" $COMMAND_NAME
       exit 1
   fi

   if [ -z "${PORT}" ] ; then          # Test for syntax error
       if [ -z "${NEW_PORT}" ] ; then          # Test for syntax error
           dspmsg chservices.cat -s 1 1 "${SERVICES_USAGE}" $COMMAND_NAME
           exit 1
       else
   	   if [ ${ACTION} = "c" ] ; then
		PORT=${NEW_PORT}
	   fi
       fi
   fi

   i=$#
   while [ $i -ne 0 ]
   do
	ALIASES=`${ECHO_CMD} ${ALIASES} $1`
	shift
        i=`expr $i - 1`
   done

# Set the default for ACTION to add.
# Set ACTION only if it has not been specified.
   ACTION=${ACTION:-"a"}

   case "${ACTION}" in
      "a")
	${GREP_CMD} "${SERVICE_NAME}.*.${PORT}/${PROTOCOL}" ${SERVICES} 2>/dev/null
	if [ $? -eq 1 ] ; then		# Then service_name is NOT in SERVICES
					# add it to the end of SERVICES
		${ECHO_CMD} "${SERVICE_NAME}	${PORT}/${PROTOCOL}	${ALIASES}" >> ${SERVICES}
	else				# Then services_name is in SERVICES
					# uncomment line and add alias(es)
					# (if not already present).

		${AWK_CMD} "/${SERVICE_NAME}.*.${PORT}\/${PROTOCOL}/   \
		{                                                      \
		    sub(\"^#\",\"\") ; recdone=1;                      \
		    split(\"${ALIASES}\",Als) ; split(\$0,Flds);       \
		    for (i in Flds) for (j in Als) {                   \
		        if (Als[j] == Flds[i]) Als[j] = \"\" ;         \
		    }                                                  \
		    printf(\"%s\",\$0) ;                               \
		    for (j in Als) if (Als[j] != \"\")                 \
		        printf(\" %s\",Als[j]) ;                       \
		    print \"\" ;                                       \
		}                                                      \
		{ if (!recdone) print ; recdone=0 ; }"                 \
		${SERVICES} > ${TMP_SERVICES} 2>/dev/null

		if [ $? != 0 ] ; then
			dspmsg chservices.cat -s 1 2 "${COMMAND_NAME}: error in updating ${SERVICES}\n" ${COMMAND_NAME} ${SERVICES}
			exit 1
		fi
		#copy the file back to /etc
		${CP_CMD} ${TMP_SERVICES} ${SERVICES} > /dev/null 2>&1
		if [ $? != 0 ] ; then
			dspmsg chservices.cat -s 1 2 "${COMMAND_NAME}: error in updating ${SERVICES}\n" ${COMMAND_NAME} ${SERVICES}
			${RM_CMD} -f ${TMP_SERVICES} > /dev/null 2>&1
			exit 1	
		fi
	fi
	;;
      "d")
echo "SERVICES " ${SERVICES}
	${GREP_CMD} "${SERVICE_NAME}.*.${PORT}/${PROTOCOL}" ${SERVICES} 2>/dev/null
	if [ $? -eq 1 ] ; then		# Then service_name is NOT in SERVICES
					# add it to the end of SERVICES
		${ECHO_CMD} "#${SERVICE_NAME}	${PORT}/${PROTOCOL}	${ALIASES}" >> ${SERVICES}
	else				# Then services_name is in SERVICES
					# comment the line.
		${SED_CMD} "\?^${SERVICE_NAME}.*.${PORT}/${PROTOCOL}?s/^/#/" ${SERVICES} > ${TMP_SERVICES} 2>/dev/null
		if [ $? != 0 ] ; then
			dspmsg chservices.cat -s 1 2 "${COMMAND_NAME}: error in updating ${SERVICES}\n" ${COMMAND_NAME} ${SERVICES}
			exit 1
		fi
		#copy the file back to /etc
		${CP_CMD} ${TMP_SERVICES} ${SERVICES} > /dev/null 2>&1
		if [ $? != 0 ] ; then
			dspmsg chservices.cat -s 1 2 "${COMMAND_NAME}: error in updating ${SERVICES}\n" ${COMMAND_NAME} ${SERVICES}
			${RM_CMD} -f ${TMP_SERVICES} > /dev/null 2>&1
			exit 1	
		fi
	fi
	;;

      "c")
	${GREP_CMD} "^${SERVICE_NAME}" ${SERVICES} 2>/dev/null
	if [ $? -eq 1 ] ; then		# Then service_name is NOT in SERVICES
					# add it to the end of SERVICES
		dspmsg chservices.cat -s 1 3 "${COMMAND_NAME}: ${SERVICE_NAME} not in ${SERVICES}\n" ${COMMAND_NAME} ${SERVICE_NAME} ${SERVICES}
		exit 1
	else				# Then services_name is in SERVICES
					# so we need to delete the old line
					# and add the new one.
		${SED_CMD} "\?^${SERVICE_NAME}.*.${PORT}\/${PROTOCOL}?d" ${SERVICES} > ${TMP_SERVICES} 2>/dev/null
		${ECHO_CMD} "${NEW_SERVICE_NAME:-${SERVICE_NAME}}	${NEW_PORT:-${PORT}}/${NEW_PROTOCOL:-${PROTOCOL}}	${ALIASES}" >> ${TMP_SERVICES}
		if [ $? != 0 ] ; then
			dspmsg chservices.cat -s 1 2 "${COMMAND_NAME}: error in updating ${SERVICES}\n" ${COMMAND_NAME} ${SERVICES}
			exit 1
		fi
		#copy the file back to /etc
		${CP_CMD} ${TMP_SERVICES} ${SERVICES} > /dev/null 2>&1
		if [ $? != 0 ] ; then
			dspmsg chservices.cat -s 1 2 "${COMMAND_NAME}: error in updating ${SERVICES}\n" ${COMMAND_NAME} ${SERVICES}
			${RM_CMD} -f ${TMP_SERVICES} > /dev/null 2>&1
			exit 1	
		fi
	fi
	;;
     esac

     if [ $? != 0 ] ; then
	dspmsg chservices.cat -s 1 2 "${COMMAND_NAME}: error in updating ${SERVICES}\n" ${COMMAND_NAME} ${SERVICES}
	exit 1
      fi

# Remove the temporary file
   ${RM_CMD} -f ${TMP_SERVICES} > /dev/null 2>&1
 }

# This following function is only for Linux, it is already available
# as a shell script file on AIX

XINETD_DIRECTORY="/etc/xinetd.d"
WEBSM_XINETD_FILE="$XINETD_DIRECTORY/websm"

function enable_in_xinetd
{
  if [ -r $WEBSM_XINETD_FILE ] ; then
   return
  fi

  if [ ! -w $XINETD_DIRECTORY ] ; then
    dspmsg websm.cat 1 "
    Cannot write to file $WEBSM_XINETD_FILE.
    Either permissions are missing or not a valid user"
    exit 0
  fi

  cat > $WEBSM_XINETD_FILE << EOF
service wsmserver
{
        socket_type             = stream
        wait                    = no
        user                    = root
        type                    = USERID
        protocol                = tcp
        server                  = /usr/websm/bin/wsmserver
        server_args             = -start
}
EOF
}

function disable_in_xinetd
{
  if [ ! -r $WEBSM_XINETD_FILE ] ; then
   return
  fi

  if [ ! -w $XINETD_DIRECTORY ] ; then
    dspmsg websm.cat 1 "
    Cannot write to file $WEBSM_XINETD_FILE.
    Either permissions are missing or not a valid user"
    exit 1
  fi

  /bin/rm -f $WEBSM_XINETD_FILE 2> /dev/null

  if [ $? != 0 ] ; then
   dspmsg websm.cat 1 "
    Couldn't delete the xinetd config file"
   exit 0
  fi


}

 function enable_or_disable
 {
   if [ "$1" = "-a" ] ; then 
     enable_in_xinetd
   else
     disable_in_xinetd
   fi
 }

 function chsubserver
 {
   TMP_INETD_CONF="/tmp/tmp.inetd.conf$$"
   XARGS_CMD="/usr/bin/xargs"
   SERVICE=
   PROTOCOL=
   SOCKET=
   WAIT=
   USER=
   PROG=
   ARGS=
   REFRESH=
   ACTION=
   NEW_SERVICE=
   NEW_PROTOCOL=
   NEW_SOCKET=
   NEW_WAIT=
   NEW_USER=
   NEW_PROG=
   NEW_ARGS=
   SUBSERVER_USAGE="
usage: ${COMMAND_NAME} [-a|-d|-c] -v service_name -p protocol [-t socket_type ] [-w ] wait_or_nowait ] [-u user ] [-g program ] [-V new_service_name ] [-P new_protocol ] [-T new_socket_type ] [-W new_wait_or_nowait ] [-U new_user ] [-G new_program ] [ -r server ] [-C config_file ] [ program_and_args ] ]\n"

# Parse the command line arguments to find out what service
# is to be uncommented and if a configuration file is specified.
# The -r server tells us to send a SIGHUP to the server.
  set -- `/usr/bin/getopt adcv:p:t:w:u:g:V:P:T:W:U:G:r:C: $*  2>/dev/null` 
  if [ $? != 0 ] ; then          # Test for syntax error
    dspmsg chsubserver.cat -s 1 1 "${SUBSERVER_USAGE}" $COMMAND_NAME
    exit 1
  fi

  enable_or_disable $1
  return

# The following will not be run because this part is only relevant if we
# use for inetd.  Since we use xinetd on Linux we don't use it for now.

  while [ "$1" != "--" ]
  do
    case $1 in
	-a|-d|-c)		# Action is to add, delete or change
	    if [ -n "${ACTION}" ] ; then dspmsg chsubserver.cat -s 1 1 "$SUBSERVER_USAGE" ${COMMAND_NAME} ; exit 1 ; fi
	    ACTION=`expr "$1" : "-\(.\)"`
	    shift		# Shift past the flag
	    ;;
	-v)			# Then we need to get the SERVICE
	    SERVICE=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and SERVICE
	    ;;
	-p)			# Then we need to get the PROTOCOL
	    PROTOCOL=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and PROTOCOL
	    ;;
	-t)			# Then we need to get the SOCKET
	    SOCKET=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and SOCKET
	    ;;
	-w)			# Then we need to get the WAIT
	    WAIT=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and WAIT
	    ;;
	-u)			# Then we need to get the USER
	    USER=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and USER
	    ;;
	-g)			# Then we need to get the PROG
	    PROG=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and PROG
	    ;;
	-V)			# Then we need to get the NEW_SERVICE
	    NEW_SERVICE=$2	# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and NEW_SERVICE
	    ;;
	-P)			# Then we need to get the NEW_PROTOCOL
	    NEW_PROTOCOL=$2	# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and NEW_PROTOCOL
	    ;;
	-T)			# Then we need to get the NEW_SOCKET
	    NEW_SOCKET=$2	# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and NEW_SOCKET
	    ;;
	-W)			# Then we need to get the NEW_WAIT
	    NEW_WAIT=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and NEW_WAIT
	    ;;
	-U)			# Then we need to get the NEW_USER
	    NEW_USER=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and NEW_USER
	    ;;
	-G)			# Then we need to get the NEW_PROG
	    NEW_PROG=$2		# to add to the inetd.conf line
	    shift; shift   	# Shift past the flag and NEW_PROG
	    ;;
	-r)			# Then we need to tell the next parameter
	    REFRESH=$2		# of the change to the configuration file.
	    shift; shift   	# Shift past the flag and server
	    ;;
	-C)			# Then we need to tell the next parameter
	    INETD_CONF=$2	# of the change to the configuration file.
	    shift; shift   	# Shift past the flag and server
	    ;;
	*)
	    dspmsg chsubserver.cat -s 1 1 "$SUBSERVER_USAGE" ${COMMAND_NAME}
	    exit 1
	    ;;
    esac
  done
  shift                   	# Shift past the "--" from getopt
 
  if [ -z "${SERVICE}" ] ; then          # Test for syntax error
    dspmsg chsubserver.cat -s 1 1 "${SUBSERVER_USAGE}" $COMMAND_NAME
    exit 1
  fi
 
  if [ -z "${PROTOCOL}" ] ; then          # Test for syntax error
    dspmsg chsubserver.cat -s 1 1 "${SUBSERVER_USAGE}" $COMMAND_NAME
    exit 1
  fi

  i=$#
  while [ $i -ne 0 ]
  do
        ARGS=`${ECHO_CMD} ${ARGS} $1`
        shift
        i=`expr $i - 1`
  done


# Set the default for ACTION to add.
# Set ACTION only if it has not been specified.
  ACTION=${ACTION:-"a"}


  case "${ACTION}" in
    "a")
	${GREP_CMD} "${SERVICE}.*.${PROTOCOL}.*.${PROG}.*.${ARGS}" ${INETD_CONF} >/dev/null 2>&1
	if [ $? -eq 1 ] ; then		# Then service_name is NOT in inetd.conf
					# add it to the end of inetd.conf
		${CP_CMD} ${INETD_CONF} ${TMP_INETD_CONF} > /dev/null 2>&1
		if [ $? -ne 0 ] ; then
			dspmsg chsubserver.cat -s 1 2 "${COMMAND_NAME}: error in updating ${INETD_CONF}\n" ${COMMAND_NAME} ${INETD_CONF}
			${RM_CMD} ${TMP_INETD_CONF} >/dev/null 2>&1
			exit 1
		fi
		${ECHO_CMD} "${SERVICE}	${SOCKET}	${PROTOCOL}	${WAIT}	${USER}	${PROG} ${ARGS}" >> ${TMP_INETD_CONF}
		if [ $? -ne 0 ] ; then
			dspmsg chsubserver.cat -s 1 2 "${COMMAND_NAME}: error in updating ${INETD_CONF}\n" ${COMMAND_NAME} ${INETD_CONF}
			${RM_CMD} ${TMP_INETD_CONF} >/dev/null 2>&1
			exit 1
		fi
	else				# Then services_name is in inetd.conf
					# Uncomment the service_name line
					# in /etc/inetd.conf
		${SED_CMD} "\?^##*${SERVICE}.*.${PROTOCOL}.*.${PROG}?s/#//
		\?^##* *${SERVICE}.*.${PROTOCOL}.*.${PROG}?s/#//" ${INETD_CONF} > ${TMP_INETD_CONF} 2>/dev/null
		if [ $? -ne 0 ] ; then
			dspmsg chsubserver.cat -s 1 2 "${COMMAND_NAME}: error in updating ${INETD_CONF}\n" ${COMMAND_NAME} ${INETD_CONF}
			${RM_CMD} ${TMP_INETD_CONF} >/dev/null 2>&1
			exit 1
		fi
	fi
	;;
    "d")
	${GREP_CMD} "${SERVICE}.*.${PROTOCOL}.*.${PROG}.*.${ARGS}" ${INETD_CONF} >/dev/null 2>&1
	if [ $? -eq 0 ] ; then		# Then services_name is in inetd.conf
					# Uncomment the service_name line
					# in /etc/inetd.conf
		${SED_CMD} "\?^#${SERVICE}.*.${PROTOCOL}.*.${PROG}?s/#//
		\?^ *${SERVICE}.*.${PROTOCOL}.*.${PROG}?s/^/#/" ${INETD_CONF} > ${TMP_INETD_CONF} 2>/dev/null
		if [ $? -ne 0 ] ; then
			dspmsg chsubserver.cat -s 1 2 "${COMMAND_NAME}: error in updating ${INETD_CONF}\n" ${COMMAND_NAME} ${INETD_CONF}
			${RM_CMD} ${TMP_INETD_CONF} >/dev/null 2>&1
			exit 1
		fi
	fi
	;;
    "c")
	${GREP_CMD} "^${SERVICE}.*.${PROTOCOL}" ${INETD_CONF} >/dev/null 2>&1
	if [ $? -eq 1 ] ; then		# Then service_name is NOT in inetd.conf
		dspmsg chsubserver.cat -s 1 3 "${COMMAND_NAME}: ${SERVICE} not in ${INETD_CONF}\n" ${COMMAND_NAME} ${SERVICE} ${INETD_CONF}
		exit 1
	else				# Then services_name is in inetd.conf
					# so we need to delete the old line
					# and add the new one.
		if [ -z "${SOCKET}" -a -z "${NEW_SOCKET}" ] ; then
		    # If not set then get the old value from the config file
		    SOCKET=`${GREP_CMD} "^${SERVICE}" ${INETD_CONF} | ${AWK_CMD} '{ print $2 }'`
		fi
		if [ -z "${WAIT}" -a -z "${NEW_WAIT}" ] ; then
		    # If not set then get the old value from the config file
		    WAIT=`${GREP_CMD} "^${SERVICE}" ${INETD_CONF} | ${AWK_CMD} '{ print $4 }'`
		fi
		if [ -z "${USER}" -a -z "${NEW_USER}" ] ; then
		    # If not set then get the old value from the config file
		    USER=`${GREP_CMD} "^${SERVICE}" ${INETD_CONF} | ${AWK_CMD} '{ print $5 }'`
		fi
		if [ -z "${PROG}" -a -z "${NEW_PROG}" ] ; then 
		    # If not set then get the old value from the config file
		    PROG=`${GREP_CMD} "^${SERVICE}" ${INETD_CONF} | ${AWK_CMD} '{ print $6 }'`
		fi
		if [ -z "${ARGS}" ] ; then 
		    # If not set then get the old value from the config file
		    ARGS=`${GREP_CMD} "^${SERVICE}" ${INETD_CONF} | ${AWK_CMD} '{ for (i = 7; i <= NF; i++); print $i }'`
		fi
		${CAT_CMD} ${INETD_CONF} | ${SED_CMD} "/^${SERVICE}.*.${PROTOCOL}/d" > ${TMP_INETD_CONF} 2>/dev/null
		if [ $? != 0 ] ; then
			dspmsg chsubserver.cat -s 1 2 "${COMMAND_NAME}: error in updating ${INETD_CONF}\n" ${COMMAND_NAME} ${INETD_CONF}
			exit 1
		fi
		${ECHO_CMD} "${NEW_SERVICE:-${SERVICE}}	${NEW_SOCKET:-${SOCKET}}	${NEW_PROTOCOL:-${PROTOCOL}}	${NEW_WAIT:-${WAIT}}	${NEW_USER:-${USER}}	${NEW_PROG:-${PROG}} ${ARGS}" >> ${TMP_INETD_CONF}
		if [ $? != 0 ] ; then
			dspmsg chsubserver.cat -s 1 2 "${COMMAND_NAME}: error in updating ${INETD_CONF}\n" ${COMMAND_NAME} ${INETD_CONF}
			exit 1
		fi
	fi
	;;
     esac



#copy the file back to /etc
   ${CP_CMD} ${TMP_INETD_CONF} ${INETD_CONF} > /dev/null 2>&1
   if [ $? != 0 ] ; then
	dspmsg chsubserver.cat -s 1 2 "${COMMAND_NAME}: error in updating ${INETD_CONF}\n" ${COMMAND_NAME} ${INETD_CONF}
	${RM_CMD} -f ${TMP_INETD_CONF} > /dev/null 2>&1
	exit 1	
   fi

   if [ $? != 0 ] ; then
	dspmsg chsubserver.cat -s 1 2 "${COMMAND_NAME}: error in updating ${INETD_CONF}\n" ${COMMAND_NAME} ${INETD_CONF}
	${RM_CMD} ${TMP_INETD_CONF} > /dev/null 2>&1
	exit 1
   fi

# Remove the temporary file
  ${RM_CMD} ${TMP_INETD_CONF} > /dev/null 2>&1

# Send signal to server, if specified
   if [ -n "${REFRESH}" ] ; then
	${PS_CMD}|${GREP_CMD} ${REFRESH}|${AWK_CMD} '{ print $1 }'|${XARGS_CMD} ${KILL_CMD} > /dev/null 2>&1
	exit $?
   fi
 }
fi

print_usage()
{
  if [[ -r ${CODEBASE}/ssl-base.zip ]] ; 
  then
    echo "\n${SERVER_NAME} [-sslalways | -ssloptional]" >&2
    echo "${SERVER_NAME} -enablehttps [port]" >&2
    echo "${SERVER_NAME} -disablehttps"  >&2
  fi

  export LANG=$LANG_SAVE

  dspmsg websm.cat 1 "
Usage:  wsmserver -enable [-listenport serverport] [-portstart port1 -portend port2 ] 
	wsmserver -disable 
	wsmserver -start
Where:
	-enable  -- Enable the server on this system
	-disable -- Disable the server
	-start   -- Start the server
	-listenport -- Specifies the port on which the server should 
		listen for connections. The default is 9090.
	-portstart -- Specifies the initial port value for the 
		range of ports that the server can use.
	-portend -- Specifies the end port of the range of ports
		that the server can use.

" wsmserver  >&2


exit 1
}

#
#
#




function refresh_server
{
   if [ "$OS" = "Linux" ] ; then
#     Send a SIGHUP to inetd process
#      PID=`ps -ef|grep  inetd|grep -v xinted|grep -v grep|awk '{print $2}'`
      PID=`ps -ef|grep  xinetd|grep -v inted|grep -v grep|awk '{print $2}'`
      if [ "$PID" != "" ] ; then
#        kill -1 $PID > /dev/null
        kill -USR2 $PID > /dev/null
      fi
   else
      refresh -s inetd > /dev/null
   fi
}

function disable_server
{

  grep "^${SERVER_NAME}[ 	]" ${SERVICES} | 
	sed 's!/.*!!;s!.*[	 ]!!' | while read sport
  do

    # Remove the websm server from /etc/services
    chservices -d -v ${SERVER_NAME} -p tcp -n $sport > /dev/null

    if [[ $? -ne 0 && $1 != "-quiet" ]] ; then
     exit 1
    fi

  done 
    
#  When we switch to 'inetd' uncomment this line

#  grep -q "^${SERVER_NAME}[ 	]" ${INETD_CONF}
#  if [[ $? -eq  0 ]] ; then

    #Remove the websm server from ${INETD_CONF}
  
    chsubserver -d -v ${SERVER_NAME} -p tcp  2>&1 > /dev/null

    if [[ $? -ne 0 && $1 != "-quiet" ]] ; then
       exit 1
    fi
#  fi

  if [[ $1 != "-quiet" ]] ; then
   refresh_server
  fi 

  return 0
}

#
#
#
function kill_server
{
	PID=$1
	if [[ -f $PORTPATH/$PID ]]
	then
		rm -f $PORTPATH/$PID ]]
	fi
	ps  -o args -p $PID | grep -sq WServer &&
	{
		kill -9 $PID || print "Could not kill WServer process" $PID && exit 1
	}
}


#
#
#
function start_server
{
	#
	# keep log file from growing too large
	#
	typeset -i lineCount
	if [[ -f $LOG_FILE ]]
	then

            if [ "$OS" = "Linux" ] ; then 
	        lineCount=`wc -l $LOG_FILE | awk '{print $1}'`
            else
	        wc -l $LOG_FILE | read lineCount junk
            fi
	    if (( $lineCount > 100 ))
	    then
		tail -80  $LOG_FILE > $LOG_FILE".replace"
		mv $LOG_FILE".replace" $LOG_FILE
	    fi
	fi
	
	#
	# try to find a 'waiting' WServer
	# if one is found then use it, otherwise start a new one
	#
	mkdir -p $PORTPATH
	#find $PORTPATH -type f -print -name \[0-9].*[0-9]$ 
	if 
	ls $PORTPATH -name [0-9]*[0-9] >/dev/null 2>&1 
	then
		sendExistingPortInfo
	else
		startNewWServer
	fi
}

#
# Validate a port number
#
function checkPort
{
	# See if value is blank
	if [[ $2 != "" ]]  ; then

	  # See if value has any non-numerics
	  echo $2 | grep -q "[^0-9]"
	  if [[ $? -ne 0 ]] ; then

	    # See if port is within valid range
	    if [[ $2 -ge 1 && $2 -le 65535 ]] ; then
		    return 0
	    fi

	  fi

	fi

	echo "$1: \c"
	dspmsg websm.cat -s 1 4 "The port value must be a number between 1 and 65535\n" >&2
	print_usage

}

#
# Set the ports to be used by the JCB server inside websm
#
function setJCBPortRange
{

  (
    set -e
	PORTSTART=$1
	PORTDIFF=$2

	if [[ ! -f ${JCB_PROPERTIES}.orig ]] ; then
		# Save a backup of the properties file

		cp ${JCB_PROPERTIES} ${JCB_PROPERTIES}.orig
	fi

	sed "s/^JC_SUPPLIER_PORT=.*/JC_SUPPLIER_PORT=$PORTSTART/;
s/^JC_SUPPLIER_PORT_RANGE=.*/JC_SUPPLIER_PORT_RANGE=$PORTDIFF/" ${JCB_PROPERTIES} > ${JCB_PROPERTIES}.new
	

	echo "\n# If WSM_USE_PORT_RANGE is set, use the JCB server port range" >> ${JCB_PROPERTIES}.new
	echo "WSM_USE_PORT_RANGE=1" >> ${JCB_PROPERTIES}.new

	mv ${JCB_PROPERTIES}.new ${JCB_PROPERTIES}


   )

   if [[ $? -ne 0 ]] ; then 
	exit 1
   fi
	
}

#
# Modify the JCB.properties file to indcate that the specific
# port range should not be used.  Delete all lines which have
# the WSM_USE_PORT_RANGE value
#
function undoJCBPortRange
{
    (

		grep -q "WSM_USE_PORT_RANGE" ${JCB_PROPERTIES}
		if [[ $? -ne 0 ]] ; then
			return 0; # Nothing to undo
		fi

	set -e

		sed "/WSM_USE_PORT_RANGE/d" ${JCB_PROPERTIES} > ${JCB_PROPERTIES}.new
		
		mv ${JCB_PROPERTIES}.new ${JCB_PROPERTIES}
    )
	
    if [[ $? -ne 0 ]] ; then
	exit 1
    fi
}


#
#
#
function enable_server
{

   PORTSTART=0
   PORTEND=0
   PortDiff=0

   if [[ $# -gt 0 ]] ; then


     while [[ $# -gt 0 ]] ; do

       if [[ $# -eq 1 ]] ; then
	 print_usage
       fi

       case $1 in 
	 -listenport) PORT="$2"  
		shift ; shift
		checkPort -listenport "$PORT"
		;;
	 -portstart ) PORTSTART="$2"
		shift;shift
		checkPort -portstart "$PORTSTART"
		;;
	 -portend ) PORTEND="$2"
		shift;shift
		checkPort -portend "$PORTEND"
		;;
	 *) print_usage 
		;;
       esac
     done


     if [[ $PORTSTART -eq 0  && $PORTEND -ne 0 ]] ; then
	print_usage
     elif [[ $PORTSTART -ne 0 && $PORTEND -eq 0 ]] ; then
	print_usage
     fi

     if [[ $PORTSTART -ne 0 ]] ; then
       (( PortDiff = $PORTEND - $PORTSTART ))

       if [[ $PortDiff -lt  2 ]] ; then
	  dspmsg websm.cat -s 1 5 "The end port value must be at least 2 greater than the start port value.\n"
	  print_usage
       fi

     fi

   fi


#   disable_server -quiet >/dev/null 2>&1
   disable_server -quiet
   chservices -a -v ${SERVER_NAME} -p tcp -n ${PORT}  
   if [ $? -ne 0 ] ; then
     exit 1
   fi

   echo "port=${PORT}" > ${CODEBASE}/inetd.properties

   if [ $? -ne 0 ] ; then
	exit 1
   fi

   chsubserver -a -v ${SERVER_NAME} -p tcp -t stream \
                      -w nowait -u root -g ${WEBSM_HOME}/bin/${SERVER_NAME} -- ${SERVER_NAME} -start
   if [[ $? -ne 0 ]] ; then
     exit 1
   fi

   if [[ $PortDiff -ne 0 ]] ; then
	setJCBPortRange $PORTSTART $PortDiff
   else
	undoJCBPortRange
   fi

   refresh_server
}


#
# send the 'waiting' port info to stdout
#
function sendExistingPortInfo
{
    #
    # use 'oldest port file'
    # 
    ls -rt $PORTPATH/[0-9].*[0-9] 2>/dev/null | head -1 | read portFile
    pid=`basename $portFile`
    portFileInUse=$portFile".in_use"

    #
    # hide the wserver so will not be re-used
    #
    mv $portFile $portFileInUse
    
    #
    # move up the priority
    #
    renice -n -15 $pid >/dev/null 2>&1 || true

    #
    # now that the existing portFile is 'in use' another should
    # be started for the next user
    #
    grep -sq -E "useWaitingServer=t|useWaitingServer=T" $CFG_FILE &&
    {
     		nice -15 ${BIN}/wjava com.ibm.websm.bridge.WServer \
		    -wait >>$LOG_FILE 2>&1 &
    }

    #
    # make sure the process id is a valid WServer process
    #
    ps  -o args -p $pid | grep -sq WServer
    if (( $? == 0 ))
    then
	    cat $portFileInUse 
	    rm -fr $portFileInUse
    else
	    rm -fr $portFileInUse
	    startNewWServer
    fi
}


#
# start a new WServer ; the inet port number is sent to stdout
#
function startNewWServer
{
    #
    # start the server which will 'wait' for the next user
    #
	grep -sq -E "useWaitingServer=t|useWaitingServer=T" $CFG_FILE &&
	{
		nice -15 ${BIN}/wjava com.ibm.websm.bridge.WServer \
	    		-wait >>$LOG_FILE 2>&1 &
	}

    #
    # Read in the language from the client. The getLang program
    # is used so that we don't accept a malicious command
    # instead of the language.
    #
    set -A args $(/usr/websm/bin/getLang)

    lang="${args[0]}"
    jcbd=""
    if [[ "${args[1]}" = "S" ]] # Debug JCB
     then
       jcbd="y"
    fi
    unset args

    #
    # start the server to use immediately
    #

    LANG=$lang JCBD=$jcbd ${BIN}/wjava com.ibm.websm.bridge.WServer\
	2>>$LOG_FILE 
}

#
#
#
enable_https()
{

 if [[ ! -r /var/websm/security/SM.privkr ]] ; then
   ls  /var/websm/security/SM.privkr
   export CLASSPATH=${CODEBASE}
   ${BIN}/wjava com.ibm.websm.bundles.FrameworkBundle SSL_NOT_CONFIGURED
   exit 1
 fi

 if [[ $1 != "" ]] ; then
 
    (( GATE_PORT = $1 ))

    if [[ $GATE_PORT != $1 ]] ; then
     # GATE_PORT is not a number
      exit 1
    fi
  fi

  #
  # If it is already configured, disable it.
  #
  disable_https  >/dev/null  2>&1

  set -e

  changeConfig https_port $GATE_PORT

  mkitab "${GATE_SERVER}:2:respawn:${BIN}/wsmserver -starthttps"


  telinit q

}

#
#
#
disable_https()
{

  changeConfig https_port ""

  rmitab ${GATE_SERVER}

  #
  # Stop any existing WGateServer processes
  #
  ps -efo pid,args | grep 'com.ibm.websm.bridge.WGateServer' |
                           awk '{print $1}' | xargs  kill -9

  telinit q
}

#
#
#
start_https()
{
  ${BIN}/wjava com.ibm.websm.bridge.WGateServer /var/websm/config/user_settings/websm.cfg >/var/websm/data/gate.log 2>&1
}

#
# Change an attribute in the websm.cfg file
#
changeConfig()
{
  set -e
  name=$1
  value=$2

  NEW_FILE=${CFG_FILE}.new

  
  sed "/$name/d" ${CFG_FILE} > ${NEW_FILE}


  if [[ $value != "" ]] ; then
    echo "$name=$value" >> ${NEW_FILE}
  fi

  mv ${NEW_FILE} ${CFG_FILE}

}


if [[ $# -eq 0 ]] ; then
  print_usage
fi

if [[ $1 = "-enablehttps" ]] ; then
  if [[ $# -gt 3 ]] ; then
    print_usage
  fi
elif [[ $1 != "-enable" && $# -ne 1 ]] ; then
  print_usage
fi

case $1 in 
  -enable)  	shift ; enable_server  $* ; exit $? ;;
  -disable) 	disable_server ;;
  -start)   	start_server ;;
  -enablehttps) enable_https $2;;
  -disablehttps) disable_https;;
  -starthttps)   	start_https ;;
  -sslalways)   	changeConfig forcessl true ;;
  -ssloptional)   	changeConfig forcessl false ;;
  *) 		print_usage x ;;
esac


